package com.cros.files;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;

public class FileHelper {

	public static boolean addTextFile(String file, String text) throws IOException {
		boolean succesfully = false;
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(file,true));
			writer.write(text);
			writer.close();
			succesfully= true;
		} catch (IOException e) {
			throw e;
		}
		return succesfully;
	}

	public static boolean createFileWithText(String path, String file, String cadena_impresa) {
		boolean valor_retorno = true;
		File fichero = new File(path, file);
		try {
			if (fichero.createNewFile()) {
				System.out.println("Se ha creado el Fichero: " + path + file);
			} else {
				System.out.println("No se ha creado el Fichero: " + path + file);
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
			valor_retorno = false;
		}

		try {
			System.out.println("Alimentando contenido al Fichero: " + path + "/" + file);
			PrintWriter fileOut = new PrintWriter(fichero);
			fileOut.println(cadena_impresa);
			fileOut.close();
			System.out.println("Contenido alimentado con exito al Fichero: " + path + "/" + file);
		} catch (IOException ioe) {
			ioe.printStackTrace();
			System.out.println("No se ha alimentado el contenido para el Fichero: "+ path + "/" + file);
			valor_retorno = false;
		}

		return valor_retorno;

	}

	public static boolean createFileWithText(String archivo, String cadena_impresa) {
		boolean valor_retorno = true;
		File fichero = new File(archivo);
		try {
			if (fichero.createNewFile()) {
				System.out.println("Se ha creado el Fichero: " + archivo);
			} else {
				System.out.println("No se ha creado el Fichero: " + archivo);
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
			valor_retorno = false;
		}

		try {
			System.out.println("Alimentando contenido al Fichero: " + archivo);
			PrintWriter fileOut = new PrintWriter(fichero);
			fileOut.println(cadena_impresa);
			fileOut.close();
			System.out.println("Contenido alimentado con exito al Fichero: " + archivo);
		} catch (IOException ioe) {
			ioe.printStackTrace();
			System.out.println("No se ha alimentado el contenido para el Fichero: "+ archivo);
			valor_retorno = false;
		}

		return valor_retorno;
	}

	
	public void move(String fromFileName, String toFileName) throws IOException {
		copy(fromFileName, toFileName);
		delete(fromFileName);
	}

	public void copy(String fromFileName, String toFileName) throws IOException {
		File fromFile = new File(fromFileName);
		File toFile = new File(toFileName);

		if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName);

		if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName);

		if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName);

		if (toFile.isDirectory()){
			toFile = new File(toFile, fromFile.getName());
		}

		if (toFile.exists()) {
			if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName);
			System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): ");
			System.out.flush();
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			String response = in.readLine();
			if (!response.equals("Y") && !response.equals("y"))
				throw new IOException("FileCopy: " + "existing file was not overwritten.");
		} else {
			String parent = toFile.getParent();
			if (parent == null){
				parent = System.getProperty("user.dir");
			}
			
			File dir = new File(parent);
			
			if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent);
			if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent);
			if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent);
		}

		FileInputStream from = null;
		FileOutputStream to = null;
		
		try {
			from = new FileInputStream(fromFile);
			to = new FileOutputStream(toFile);
			byte[] buffer = new byte[4096];
			int bytesRead;

			while ((bytesRead = from.read(buffer)) != -1){
				to.write(buffer, 0, bytesRead); // write
			}
		} catch(IOException ioe){
			throw ioe;
		}finally {
			if (from != null)
				try {
					from.close();
				} catch (IOException e) {
					throw e;
				}
			if (to != null)
				try {
					to.close();
				} catch (IOException e) {
					throw e;
				}
		}
	}

	public static void delete(String fileName) {
		// A File object to represent the filename
		File f = new File(fileName);

		// Make sure the file or directory exists and isn't write protected
		if (!f.exists()) throw new IllegalArgumentException( "Delete: no such file or directory: " + fileName);

		if (!f.canWrite()) throw new IllegalArgumentException("Delete: write protected: " + fileName);

		// If it is a directory, make sure it is empty
		if (f.isDirectory()) {
			String[] files = f.list();
			if (files.length > 0) throw new IllegalArgumentException( "Delete: directory not empty: " + fileName);
		}

		// Attempt to delete it
		boolean success = f.delete();

		if (!success)
			throw new IllegalArgumentException("Delete: deletion failed");
	}

	public static String getNameFile(String in) {
		String name = null;
		File fichero = new File(in);
		if (!fichero.exists()) throw new IllegalArgumentException( "getNameFile: File doesnt exist!!: " +  in);
		else{
			name = fichero.getName();
		}
		
		return name;
	}
	
	public static String readFile(String path) throws IOException{
		try{
			/*Path Example
			 * C:\\htmlMaildeRapido\\index.html
			 */
			
			 BufferedReader br=null;
			 FileInputStream fstream = new FileInputStream(path); 
			 System.out.println("the directory exists available = " + fstream.available());
			 DataInputStream in = new DataInputStream(fstream);
			 br = new BufferedReader(new InputStreamReader(in));
			 String strLine;
			 StringBuilder temporal = new StringBuilder();
			  while ((strLine = br.readLine()) != null)   {
				  temporal.append(strLine);
			  }
			 in.close();
			 
			 return strLine.toString();

		}catch(IOException e){
			e.printStackTrace();
			throw e;
		}
	}
	
	
	public void crearDirectorio() {
			 // Creamos el nombre de un directorio mediante un objeto File
			   // El directorio raiz debe de existir -- mkdir --
			   File directorio = new File("c:\\temp\\directorio");

			   if (directorio.mkdir())
			     System.out.println("Se ha creado directorio");
			   else
			     System.out.println("No se ha podido crear el directorio");

			   // El directorio raiz no tiene pq existir -- mkdirs    --
			   File directorio2 = new File("c:\\temp\\directorio\\lineadecodigo\\java_io\\hola");
			   if (directorio2.mkdirs())
			     System.out.println("Se ha creado directorio");
			   else
			     System.out.println("No se ha podido crear el directorio"); 
			
		}

	}

